import pygame # 导入模块
from pygame.locals import *
pygame.init()  # 初始化模块
size = width,height = 800,600
screen = pygame.display.set_mode(size)  # 创建一个Surface对象窗口
pygame.display.set_caption("Pong游戏")  # 设置标题
keep_going = True  # 循环标志
BLACK = (0,0,0)
clock = pygame.time.Clock()

# 挡板
WHITE = (255,255,255)
paddle_width = 200 # 挡板宽度
paddle_height = 25 # 挡板高度
paddle_x = 300    # 挡板left属性
paddle_y = 550    # 挡板top属性

# 笑脸图片
pic = pygame.image.load("Smile.bmp").convert_alpha()_at((0,0))
colorkey = pic.get
pic.set_colorkey(colorkey)

# 速度和位置
speedx = 5
speedy = 5
pic_x = 0
pic_y = 0

# 得分和生命值
points = 0
lives = 5

# 从系统字库创建一个Font对象
font = pygame.font.SysFont("simhei",24)

# 添加背景音乐
pygame.mixer.init()  # 初始化
pygame.mixer.music.load("bgm.wav")
pygame.mixer.music.set_volume(0.2)
pygame.mixer.music.play()

# 添加音效
pop = pygame.mixer.Sound("pop.wav")
pop.set_volume(0.5)

while keep_going:
    for event in pygame.event.get():
        if event.type == QUIT:
            keep_going = False

        if event.type == KEYDOWN:  # 重新开始游戏
            if event.key == K_F1 and lives == 0:
                points = 0
                lives = 5
                pic_x = 0
                pic_y = 0
                speedx = speedy = 5
                pygame.mixer.music.play() # 播放背景音乐

    pic_x += speedx
    pic_y += speedy

    # 墙壁碰撞检测
    if pic_x <= 0 or pic_x + pic.get_width() >= width:
        speedx = - speedx * 1.1 # 加快速度

    if pic_y <= 0:
        speedy = -speedy + 1
        
    if pic_y >= height - pic.get_height():
        lives -= 1   # 减少一条命
        speedy = -5
        speedx = 5
        pic_y = height - pic.get_height() -1

    screen.fill(BLACK) # 填充背景

    # 绘制挡板
    paddle_x = pygame.mouse.get_pos()[0]
    paddle_x -= paddle_width/2
    pygame.draw.rect(screen,WHITE,(paddle_x,paddle_y,paddle_width,paddle_height))

    # 绘制笑脸图片
    screen.blit(pic,(pic_x,pic_y))

    # 笑脸和挡板碰撞检测，得分加1
    if pic_y + pic.get_height() >= paddle_y and pic_y + pic.get_height() <= \
       paddle_y + paddle_height and speedy > 0:
        if pic_x + pic.get_width()/2 >= paddle_x and pic_x + pic.get_width()/2\
           <= paddle_x + paddle_width:
            pop.play()  # 播放碰撞音效
            points += 1
            speedy = -speedy

    # 游戏结束
    if lives < 1:
        speedx = speedy = 0  # 笑脸速度为0，便不会运动了
        lives = 0
        pygame.mixer.music.stop()
        gv_str = "游戏结束，你的得分是：" + str(points)
        gv_str += " 。按F1键继续游戏！！"
        gv_text = font.render(gv_str,True,(255,0,0))
        gv_text_rect = gv_text.get_rect()
        gv_text_rect.center = screen.get_rect().center # 屏幕中央
        screen.blit(gv_text,gv_text_rect)

    # 显示文本字符串
    draw_text ="生命值：" + str(lives) + " 得分: " + str(points)        
    text = font.render(draw_text,True,WHITE)
    text_rect = text.get_rect()
    text_rect.centerx = screen.get_rect().centerx # 水平居中
    text_rect.y = 10
    screen.blit(text,text_rect)
    
    pygame.display.flip()
    clock.tick(60) # 设置帧速率

pygame.quit()